import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    shopList: [{
      list: [],
      // 添加ID
      shuID: 1,
      // 选中ID
      judges: 0,
      // 修改数据,
      modify: {},
      goods_id: 57332,
      goods_name: '400毫升 海鲜食品冷藏冰包 注水冰袋医用冰袋户外冷藏保鲜熟食冷藏反复使用（10个装）',
      goods_price: '14.00',
      goods_number: '2',
      goods_small_logo: "https://img.yzcdn.cn/vant/t-thirt.jpg",
      checked: true
    }, {
      goods_id: 57333,
      goods_name: '400毫升 海鲜食品冷藏冰包 注水冰袋医用冰袋户外冷藏保鲜熟食冷藏反复使用（10个装）',
      goods_price: '20.00',
      goods_number: '3',
      goods_small_logo: "https://img.yzcdn.cn/vant/t-thirt.jpg",
      checked: true
    }, ],
    // 计算价格
    shopPrice: 0,
    // 总数
    allNum: 0,
    shopList:[],
  },
  mutations: {
    addShopList(state,val) {
      state.shopList.push(val)
    },
    allNum: 0
  },
  mutations: {
    //   函数
    changePrice(state, {
      id,
      num
    }) {
      state.shopList.forEach(x => {
        if (x.goods_id === id) {
          x.goods_number = num
        }
      })
      state.shopPrice = 0
      state.allNum = 0
    },
     // 添加地址
     AdTheAddress(state, val) {
      console.log(val)
      const data = localStorage.getItem('list')
      state.list = JSON.parse(data)
      if (data === null) {
        state.list = []
      }
      state.shuID = localStorage.getItem('shuID')

      state.list.push(val)
      // 判断默认地址是否为true
      if (val.isDefault) {
        // 遍历默认地址都为false
        state.list.forEach(item => {
          item.isDefault = false
        })
        // 
        const res = state.list.find(item => {
          return val.id == item.id
        })
        console.log(res)
        res.isDefault = true
        state.judges = state.shuID
      }
      state.shuID = (+state.shuID + 1)
      console.log(val)

      localStorage.setItem('list', JSON.stringify(state.list))
      localStorage.setItem('shuID', JSON.stringify(state.shuID))
    },
    // 赋值选中的ID
    addSelect(state, id) {
      state.judges = id
    },
    // 修改数据
    addModify(state, val) {
      state.modify = val
      console.log(state.modify)
    },
    addlistk(state) {
      const data = localStorage.getItem('list')
      state.list = JSON.parse(data)
      state.shuID = localStorage.getItem('shuID')
      if (state.shuID === null) {
        state.shuID = 1
      }
      state.judges = state.shuID
    }
  
    
  },
  getters: {
    //   计算属性
    // 计算总价
    changeTotle(state) {
      state.shopList.forEach(x => {
        let totle = x.goods_price * x.goods_number * 100
        state.shopPrice = state.shopPrice + totle
      })
      return state.shopPrice
    },
    // 计算总数
    changeNum(state) {
      state.shopList.forEach(x => {
        let totleNum = parseInt(x.goods_number)
        state.allNum = state.allNum + totleNum
      })
      return state.allNum
    }
  },
})

// import Vue from 'vue'
// import Vuex from 'vuex'
// Vue.use(Vuex)



